package com.noble.glamour.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;

import com.noble.glamour.bean.center.user.detail.UserDetail;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.BaseFragment;
import com.noble.glamour.module.logic.config.FinalKey;
import com.noble.glamour.module.logic.socket.IMProxy;
import com.noble.glamour.module.util.TimerUtil;
import com.noble.glamour.module.util.UIShow;
import com.noble.library.base.BaseAppCompatActivity;
import com.noble.library.host.Hosts;
import com.noble.library.log.PToast;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.library.observe.PObserver;
import com.noble.library.permission.PermissionUtil;
import com.noble.meether.R;
import com.noble.meether.chat.unread.UnreadMgrImpl;
import com.noble.meether.chat.unread.view.BadgeView;
import com.noble.meether.fragment.mail.MailFragment;
import com.noble.meether.fragment.rob.RobFragment;
import com.noble.meether.fragment.start.StartFragment;
import com.noble.meether.fragment.user.UserFragment;

public class MainActivity extends BaseAppCompatActivity implements View.OnClickListener, PObserver {

    private FragmentManager fragmentManager;
    private MailFragment mailFragment;             // 消息
    private UserFragment userFragment;             // 我的
    private BaseFragment homeFragment;              // 女性：抢聊大厅   男性： 发起聊天

    private BaseFragment current;  // 当前的fragment
    private static View[] views;

    private BadgeView mail_num;

    private UserDetail userDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isCanBack(false);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_act);
        detectFileUriExposure();
        initViews();
        initFragment();
        initData();
        permission();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!ModuleMgr.getLoginMgr().checkAuthIsExist()) {
            PToast.showShort("登录失效，请重新登录");
            UIShow.showNavUserAct(this);
            finish();
        }
    }

    @Override
    protected boolean isStatusBarLight() {
        return false;
    }

    /**
     * 权限授权
     */
    private void permission() {
        // 延迟检测，键盘未关闭布局异常
        MsgMgr.getInstance().delay(this, () -> PermissionUtil.checkAVPermission(MainActivity.this, null), 1500);
    }

    private void initData() {
        Hosts.initWebAppUrl();
        ModuleMgr.getCommonMgr().reqNewVersion(null);      // 检查升级
        ModuleMgr.getCommonMgr().reqSettingAll(null);      // 在线配置
        ModuleMgr.getCommonMgr().requestGiftList(null);     // 获取礼物列表
        ModuleMgr.getCommonMgr().reqGetComplainReasons(null); // 获取投诉列表
        ModuleMgr.getCommonMgr().getNoticeMsg();  // 获取公告消息
        ModuleMgr.getUnreadMgr().registerBadge(mail_num, false, UnreadMgrImpl.MAIL);
        IMProxy.getInstance().connect();//连接socket

        MsgMgr.getInstance().attach(this);
    }

    private void initFragment() {
        fragmentManager = getSupportFragmentManager();
        mailFragment = (MailFragment) new MailFragment().setSortTag(0);
        userFragment = (UserFragment) new UserFragment().setSortTag(2);
        if (userDetail.isMan()) {
            homeFragment = new StartFragment().setSortTag(1);
        } else {
            homeFragment = new RobFragment().setSortTag(1);
        }
        switchContent(homeFragment);
    }

    private void initViews() {
        userDetail = ModuleMgr.getCenterMgr().getMyInfo();
        View mail_layout = findViewById(R.id.mail_layout);
        View user_layout = findViewById(R.id.user_layout);
        View home_layout = findViewById(R.id.home_layout);

        views = new View[]{mail_layout, user_layout, home_layout};

        mail_layout.setOnClickListener(this);
        user_layout.setOnClickListener(this);
        home_layout.setOnClickListener(this);

        // 角标
        mail_num = findViewById(R.id.mail_number);
    }

    /**
     * 切换当前显示的fragment
     */
    private void switchContent(BaseFragment fragment) {
        tabSwitchStatus(fragment);

        if (current != fragment) {
            FragmentTransaction transaction;
            if (current == null) {
                transaction = fragmentManager.beginTransaction();
            } else {
                boolean animType = current.getSortTag() > fragment.getSortTag();

                int enter = animType ? R.anim.slide_left_in : R.anim.slide_right_in;
                int exit = animType ? R.anim.slide_right_out : R.anim.slide_left_out;
                transaction = fragmentManager.beginTransaction()
                        .setCustomAnimations(enter,
                                exit);
                transaction.hide(current);
            }

            if (!fragment.isAdded()) { //先判断是否被add过
                transaction.add(R.id.content, fragment).commitAllowingStateLoss();
            } else {
                transaction.show(fragment).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
            }
            fragmentManager.executePendingTransactions();
            current = fragment;
        }
    }

    /**
     * fragment切换的时候的状态判断以及请求
     *
     * @param fragment 切换的fragment
     */
    private void tabSwitchStatus(BaseFragment fragment) {
        if (fragment == mailFragment) {
            tabSwitchHandler.sendEmptyMessage(R.id.mail_layout);
        } else if (fragment == userFragment) {
            tabSwitchHandler.sendEmptyMessage(R.id.user_layout);
        } else if (fragment == homeFragment) {
            tabSwitchHandler.sendEmptyMessage(R.id.home_layout);
        }
    }

    private static Handler tabSwitchHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            for (View view : views) {
                // 底部tab选中效果
                view.setSelected(msg.what == view.getId());
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mail_layout:
                switchContent(mailFragment);
                break;
            case R.id.user_layout:
                switchContent(userFragment);
                break;
            case R.id.home_layout:
                switchContent(homeFragment);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == 200) {
            UIShow.showNavUserAct(this);
            finish();
        }
    }

    /**
     * 切换首页tab
     *
     * @param tab_type tab类型
     */
    public void changeTab(int tab_type) {
        if (FinalKey.MAIN_TAB_1 == tab_type) {//跳转聊天大厅
            switchContent(homeFragment);
        }
    }

    private long firstExitTime = 0;// 用于判断双击退出时间间隔

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            long doubleExitTime = System.currentTimeMillis();
            if (doubleExitTime - firstExitTime < 2000) {
                finish();//假退出，只关闭当前页面
            } else {
                firstExitTime = doubleExitTime;
                PToast.showShort(getResources().getString(R.string.tip_quit));
            }
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    // ================================= 未读角标管理 ==============================================


    @Override
    public void onMessage(String key, Object value) {
        switch (key) {
            case MsgType.MT_Unread_change:
                TimerUtil.beginTime(() -> ModuleMgr.getUnreadMgr().onMsgNum(mail_num, UnreadMgrImpl.MAIL), 200);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MsgMgr.getInstance().detach(this);
    }
}
